package com.lcp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcp.entity.TcmKnowledgeComment;
import com.lcp.mapper.TcmKnowledgeCommentMapper;
import com.lcp.service.TcmKnowledgeCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TcmKnowledgeCommentServiceImpl implements TcmKnowledgeCommentService {

    @Autowired
    private TcmKnowledgeCommentMapper tcmKnowledgeCommentMapper;

    @Override
    public TcmKnowledgeComment getById(Long id) {
        return tcmKnowledgeCommentMapper.selectById(id);
    }

    @Override
    public IPage<TcmKnowledgeComment> pageByKnowledgeId(Long knowledgeId, Integer pageNum, Integer pageSize) {
        QueryWrapper<TcmKnowledgeComment> wrapper = new QueryWrapper<>();
        wrapper.eq("knowledge_id", knowledgeId)
            .eq("status", "NORMAL")
            .isNull("parent_id")
            .orderByDesc("create_time");
            
        return tcmKnowledgeCommentMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public List<TcmKnowledgeComment> listByParentId(Long parentId) {
        QueryWrapper<TcmKnowledgeComment> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId)
            .eq("status", "NORMAL")
            .orderByAsc("create_time");
            
        return tcmKnowledgeCommentMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public TcmKnowledgeComment create(TcmKnowledgeComment comment) {
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setLikeCount(0);
        comment.setStatus("NORMAL");
        
        tcmKnowledgeCommentMapper.insert(comment);
        return comment;
    }

    @Override
    @Transactional
    public TcmKnowledgeComment update(TcmKnowledgeComment comment) {
        comment.setUpdateTime(LocalDateTime.now());
        tcmKnowledgeCommentMapper.updateById(comment);
        return comment;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        tcmKnowledgeCommentMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void incrementLikeCount(Long id) {
        TcmKnowledgeComment comment = tcmKnowledgeCommentMapper.selectById(id);
        if (comment != null) {
            comment.setLikeCount(comment.getLikeCount() + 1);
            tcmKnowledgeCommentMapper.updateById(comment);
        }
    }
} 